package com.lagou.config;

import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import javax.servlet.ServletException;
import java.io.File;

/**
 * Tomcat启动类
 * 负责Tomcat的创建和启动
 */
public class SpringApplication {
    public static void run() {
        try {
            // 创建Tomcat服务器
            Tomcat tomcat = new Tomcat();
            // 指定端口号
            tomcat.setPort(8080);
            // 指定静态资源路径
            StandardContext standardContext = (StandardContext) tomcat.addWebapp("/", new File("src/main").getAbsolutePath());
            // 禁止重新载入
            standardContext.setReloadable(false);
            // class文件地址
            File file = new File("target/classes");
            // 创建WebRoot
            WebResourceRoot resourceRoot = new StandardRoot(standardContext);
            // Tomcat内部读取class执行
            resourceRoot.addJarResources(new DirResourceSet(resourceRoot, "/WEB-INF/classes", file.getAbsolutePath(), "/"));
            // 启动Tomcat
            tomcat.start();
            System.out.println("Tomcat服务器启动成功...");
            // 异步接收请求
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
